{include file='header'/}
<style type="text/css">
    .releasetips {
        position: relative;
    }

    .releasetips i {
        display: block;
        background: #f00;
        border-radius: 50%;
        width: 0.3em;
        height: 0.3em;
        top: 0px;
        right: -8px;
        position: absolute;
        box-shadow: 0px 0px 2px #f11414;
    }
</style>
<body class="pear-container pear-admin">
<div class="layui-card">
    <div class="alert alert-info-light">
        <b>温馨提示</b><br>
        1、插件在线安装，升级和购买需要注册HuiCMS官网账号,请点击下方【会员信息】，点击【注册】按钮<br>
        2、点击插件名称可查看详情，截图和日志等信息
    </div>
</div>
<input type="hidden" name="category_id" value="0">
<div class="layui-card">
    <div class="layui-card-body">
        <table class="layui-hide" id="addonTable" lay-filter="addonTable"></table>
    </div>
</div>

<script type="text/html" id="add_toolbar">
    <button class="pear-btn pear-btn-success pear-btn-sm" id="faupload-addon" data-type="file" lay-event="file">
        <i class="layui-icon layui-icon-add-circle"></i>
        本地安装
    </button>
    <a href="{:url('addon/index')}" class="pear-btn {if($type=='online')}pear-btn-zise{/if} pear-btn-sm"
       data-type="all">
        <i class="layui-icon layui-icon-align-left"></i>
        全部
    </a>
    <a href="{:url('addon/index',['type'=>'local'])}"
       class="pear-btn {if($type=='local')}pear-btn-zise{/if} pear-btn-sm" data-type="local">
        <i class="layui-icon layui-icon-app"></i>
        本地插件
    </a>
    <button class="pear-btn pear-btn-black pear-btn-sm btn-userinfo" lay-event="userinfo">
        <i class="layui-icon layui-icon-username"></i>
        会员信息
    </button>
    <div class="layui-input-inline" style="width:120px;margin-left:20px;">
        <input type="text" id="searchInput" placeholder="请输入关键词" autocomplete="off" class="layui-input"
               style="height:32px;">
    </div>
    <button class="layui-btn layui-btn-sm" lay-event="search">搜索</button>
</script>

<script type="text/html" id="titleTpl">
    <div>
        {{# if(d.url){ }}
        {{# if(d.name != 'recommend' ){ }}
        <a href="javascript:;" data-url="{{d.url}}" lay-tips="查看插件介绍和帮助" title="插件详情" class="btn-dialog">{{=
            d.title }}</a>
        {{# } else { }}
        <a href="{{= d.url}}" target="_blank" lay-tips="查看插件介绍和帮助">{{= d.title }}</a>
        {{# } }}
        {{# } else { }}
        <a href="javascript:;">{{= d.title }}</a>
        {{# } }}
    </div>
</script>

<script type="text/html" id="operateTpl">
    {{#  if(d.addon){ }}
    {{# if(d.addon.version!=d.version){ }}
    {{# if(typeof d.releaselist !="undefined" && d.releaselist.length>1){ }}
    <a class="layui-btn layui-btn-xs layui-btn-normal" data-name="{{d.name}}" data-version="{{d.version}}"
       data-title="{{d.title}}" data-value="{{= JSON.stringify(d.releaselist)}}" lay-event="upgrade">升级 <i
            class="layui-icon layui-icon-down"></i></a>
    {{# }else if(typeof d.releaselist !="undefined" && d.releaselist.length>0){ }}
    <a class="layui-btn layui-btn-xs layui-btn-normal btn-upgrade" data-name="{{d.name}}" data-version="{{d.version}}"
       data-title="{{d.title}}">升级</a>
    {{#  } }}
    {{#  } }}

    {{#  if(d.addon.config == 1 ){ }}
    <a class="layui-btn layui-btn-xs btn-dialog" href='{:url("config")}?name={{d.name}}'
       title="插件设置 -【{{d.title}}】">设置</a>
    {{#  } }}

    <a class="layui-btn layui-btn-xs layui-btn-danger btn-uninstall" data-name="{{d.name}}"
       data-status="{{d.addon.status}}" data-title="确定卸载【{{d.title}}】，进行该操作？" confirm>卸载</a>
    {{#  } else { }}
    {{# if(typeof d.releaselist !="undefined" && d.releaselist.length>1){ }}
    <a class="layui-btn layui-btn-xs" data-name="{{d.name}}" data-version="{{d.version}}"
       data-title="确定安装【{{d.title}}】，进行该操作？" data-value="{{= JSON.stringify(d.releaselist)}}"
       lay-event="install">安装 <i class="layui-icon layui-icon-down"></i></a>
    {{# }else if(typeof d.releaselist !="undefined" && d.releaselist.length>0){ }}
    <a class="layui-btn layui-btn-xs btn-install" data-name="{{d.name}}" data-version="{{d.version}}"
       data-title="确定安装【{{d.title}}】，进行该操作？">安装</a>
    {{#  } }}

    {{# if(d.button){ }}
    <a href="{{d.url}}" class="layui-btn layui-btn-xs layui-btn-normal" target="_blank">
        {{d.button}}
    </a>
    {{#  } }}
    {{#  } }}
</script>

<script id="statusTpl" type="text/html">
    {{#  if(d.addon){ }}
    <input type="checkbox" name="status" value="{{d.id}}" lay-skin="switch" lay-text="启用|禁用"
           lay-filter="switchStatus"
           data-href="{:url('addon/status')}?id={{d.id}}&field=status&name={{d.name}}" {{d.status== '1' ? 'checked' : '' }} />
    {{#  } }}
</script>

<script id="uninstalltpl" type="text/html">
    <div class="">
        <div class="">{{ d.title }}
            <p class="text-danger">卸载将会删除所有插件文件且不可找回!!! </p>
            {if env('APP_DEBUG')}
            <p class="text-danger">
                <label>
                    <input type="checkbox" name="droptables" id="droptables" data-name="{{ d.name }}"/>
                    删除所有插件相关数据表且不可找回!!!
                </label>
            </p>
            {/if}
            <p class="text-danger">如有重要数据请备份后再操作!!!</p>
        </div>
    </div>
</script>

<script id="logintpl" type="text/html">
    <div style="padding:20px;">
        <form class="layui-form">
            <div class="alert alert-danger-light">
                <strong>温馨提示</strong><br/>此处登录账号为<a href="http://huicmf.xiaohuihui.club/" target="_blank">HuiCMF官网账号</a>
            </div>
            <div class="layui-form-item">
                <div class="layui-input-wrap">
                    <div class="layui-input-prefix">
                        <i class="layui-icon layui-icon-username"></i>
                    </div>
                    <input type="text" class="layui-input" id="inputAccount" value="" autocomplete="off"
                           placeholder="你的手机号、用户名或邮箱" required>

                </div>
            </div>
            <div class="layui-form-item">
                <div class="layui-input-wrap">
                    <div class="layui-input-prefix">
                        <i class="layui-icon layui-icon-password"></i>
                    </div>
                    <input type="password" class="layui-input" id="inputPassword" value="" autocomplete="off"
                           lay-affix="eye" placeholder="你的密码" required>

                </div>
            </div>
        </form>
    </div>
</script>

<script id="userinfotpl" type="text/html">
    <div>
        <form class="form-horizontal form-userinfo">
            <div class="alert alert-dismissable alert-info-light">
                <strong>温馨提示</strong><br/>你好！{{d.username}}<br/>当前你已经登录，将同步保存你的购买记录
            </div>
        </form>
    </div>
</script>

{include file='footer'/}
<script>
  layui.use(['form', 'table', 'util', 'admin', 'laydate', 'element', 'upload'], function ($, Table) {
    var $ = layui.jquery;
    var form = layui.form;
    var table = layui.table;
    var upload = layui.upload;
    form.render();

    var addonTable = table.render({
      elem: '#addonTable'
      , toolbar: '#add_toolbar'
      , defaultToolbar: [{
        layEvent: 'refresh',
        icon: 'layui-icon-refresh',
        title: '刷新'
      }, 'filter', 'exports']
      , method: 'get'
      , url: "{:url('addon/index')}"
      , where: {type: '{$type}', search: ''}
      , css: '.layui-table-tool-temp{padding-right: 85px;}'
      , showSearch: false
      , parseData: function (res) {
        return {
          "code": 0,
          "msg": res.msg,
          "count": res.count,
          "data": res.data
        };
      }
      , cellMinWidth: 100
      , cols: [[
        {field: 'title', width: 200, title: '名称', templet: '#titleTpl'},
        {field: 'name', width: 150, title: '标识'},
        {field: 'description', title: '描述'},
        {field: 'author', width: 90, title: '作者'},
        {
          field: 'price',
          width: 95,
          title: '价格',
          hide: "{$type}=='local'" ? true : false,
          templet: function (d) {
            if (isNaN(d.price)) {
              return d.price;
            }
            return parseFloat(d.price) == 0 ? '<span class="text-success">' + '免费' + '</span>' : '<span class="text-danger">￥' + d.price + '</span>';
          }
        },
        {field: 'downloads', width: 90, title: '下载', hide: "{$type}=='local'" ? true : false},

        {
          field: 'version',
          width: 80,
          title: '版本',
          templet: function (d) {
            return d.addon && d.addon.version != d.version ? '<a href="javascript:;"><span class="releasetips text-primary" lay-tips="发现新版本:' + d.version + '">' + d.addon.version + '<i></i></span></a>' : d.version;
          }
        },
        {field: 'status', width: 90, title: '状态', templet: '#statusTpl'},
        {fixed: 'right', width: 180, title: '操作', templet: '#operateTpl'}
      ]]
      , page: true
      , limit: 10
      , done: function (res, curr, count) {
        var searchKeyword = res.msg || "";
        $('#searchInput').val(searchKeyword);
      }
    });

    // 上传附件
    upload.render({
      elem: '#faupload-addon',
      url: GV.file_upload_url,
      field: "file",
      accept: "file",
      exts: "zip",
      choose: function (obj) {
        console.log(obj)
      },
      before: function (obj) {
        console.log(obj)
      },
      progress: function (n, elem, res, index) {
        var percent = n + '%'
        console.log(percent)
      },
      done: function (res) {
        if (res.code !== 200) {
          layer.msg(res.msg)
          return false;
        }
        var file_load = layer.load();
        //layer.msg("上传成功，等待插件安装", {icon: 1, time: 1700});
        $.post("{:url('addon/local')}", {file_url: res.url}, function (res_file) {
          layer.close(file_load)
          if (res_file.code !== 200) {
            layer.msg(res_file.msg, {icon: 2, time: 1500})
            return false;
          }
          testdata = res_file.data.testdata;
          layer.alert('安装成功！清除浏览器缓存和框架缓存后生效！' + (testdata ? '<br>你还可以继续导入测试数据！' : ""), {
            btn: testdata ? ['导入测试数据', '暂不导入'] : ['确定'],
            title: '温馨提示',
            yes: function (index) {
              if (testdata) {
                /*Yzn.api.ajax({
                  url: 'addon/testdata',
                  data: {
                    name: addon.name,
                  }
                }, function(data, res) {
                  Layer.close(index);
                });*/
              } else {
                layer.close(index);
                window.location.href = "{:url('addon/index',['type'=>'local'])}"
              }
            },
            icon: 1
          });
          return true;
        })
      }
    });

    table.on('toolbar(addonTable)', function (obj) {
      if (obj.event === 'refresh') {
        table.reload('addonTable');
      } else if (obj.event === 'userinfo') {
        btn_userinfo();
      }  else if (obj.event === 'search') {
        var keyword = $('#searchInput').val();
        table.reload('addonTable', {
          where: {search: keyword, type: '{$type}'}
        });
      }
    });

    // 点击卸载
    $(document).on("click", ".btn-uninstall", function () {
      var name = $(this).data('name');
      var title = $(this).data('title');
      if ($(this).data('status') == 1) {
        layer.alert('请先禁用插件再进行卸载', {icon: 7});
        return false;
      }
      layer.confirm(layui.laytpl($("#uninstalltpl").html()).render({
        name: name,
        title: title
      }), function (index, layero) {
        uninstall(name, false, $("input[name='droptables']", layero).prop("checked"));
      });
    });

    function btn_userinfo() {
      var that = this;
      var area = [$(window).width() > 800 ? '500px' : '95%', $(window).height() > 600 ? '400px' : '95%'];
      var userinfo = localStorage.getItem('huicmf_userinfo');
      if (!userinfo) {
        layer.open({
          content: layui.laytpl($("#logintpl").html()).render({}),
          type: 1,
          zIndex: 99,
          area: area,
          title: '登录',
          resize: false,
          btn: ['登录', '注册'],
          yes: function (index, layero) {
            var account = $("#inputAccount", layero).val();
            var password = $("#inputPassword", layero).val();
            if (account === '') {
              layer.msg('请输入账号', {icon: 2, time: 1500});
              return false;
            }
            if (password === '') {
              layer.msg('请输入密码', {icon: 2, time: 1500});
              return false;
            }
            params = {
              account: account,
              password: password,
            }
            $.ajax({
              type: "post",
              url: "https://api.yzncms.com/user/login",
              dataType: "json",
              data: params,
              success: function (res) {
                if (res.code === 200 || res.code === 1) {
                  // 登录成功，可以执行其他操作，例如存储用户信息
                  localStorage.setItem('huicmf_userinfo', JSON.stringify(res.data));
                  layer.msg(res.msg, {icon: 1, time: 1500}, function () {
                    layer.close(index); // 关闭弹窗
                  });
                } else if (res.code === 0) {
                  // 登录失败，但不关闭弹窗
                  layer.msg(res.msg, {icon: 2, time: 1500});
                  return false;
                } else {
                  // 登录失败，但不关闭弹窗
                  layer.msg(res.msg, {icon: 2, time: 1500});
                  return false;
                }
              },
              error: function () {
                layer.msg('请求失败，请重试！', {icon: 2, time: 1500});
              }
            })
            return false;
          },
          btn2: function () {
            return false;
          },
          success: function (layero, index) {
            this.checkEnterKey = function (event) {
              if (event.keyCode === 13) {
                $(".layui-layer-btn0").trigger("click");
                return false;
              }
            };
            $(document).on('keydown', this.checkEnterKey);
            $(".layui-layer-btn1", layero).prop("href", "https://www.yzncms.com/index/user/register.html").prop("target", "_blank");
          },
          end: function () {
            $(document).off('keydown', this.checkEnterKey);
          }
        })
      } else {
        userinfo = JSON.parse(userinfo);
        userinfo = userinfo.userinfo;
        $.ajax({
          type: "post",
          url: "/index/index/login_index",
          dataType: "json",
          data: {uid: userinfo.id, token: userinfo.token},
          success: function (res) {
            layer.open({
              content: layui.laytpl($("#userinfotpl").html()).render(userinfo),
              area: area,
              title: '会员信息',
              resize: false,
              btn: ['退出登录', '关闭'],
              yes: function () {
                $.ajax({
                  url: 'https://api.yzncms.com/user/logout',
                  data: {uid: userinfo.id, token: userinfo.token},
                  type: "post",
                  dataType: "json",
                  success: function (res2) {
                    localStorage.setItem('huicmf_userinfo', '');
                    layer.closeAll();
                    layer.alert(res2.msg, {title: '温馨提示', icon: 0});
                  }
                })
              }
            });
            return false;
          }, error: function () {
            layer.msg('接口请求失败！', {icon: 2, time: 2000});
          }
        })
      }
    }

    // 判断是否登录
    var isLogin = function () {
      var userinfo = localStorage.getItem('huicmf_userinfo');
      var uid = userinfo ? userinfo.id : 0;

      if (parseInt(uid) === 0) {
        var index_alert = layer.alert('你当前未登录Huicmf，请登录后操作！', {
          title: '温馨提示',
          btn: ['立即登录'],
          yes: function (index, layero) {
            $(".btn-userinfo").trigger("click");
            layer.close(index_alert);
          },
        });
        return false;
      }
      return true;
    }

    // 卸载模块
    var uninstall = function (name, force, droptables) {
      $.ajax({
        url: "{:url('addon/uninstall')}",
        data: {name: name, force: force ? 1 : 0, droptables: droptables ? 1 : 0}
      }, function (data, res) {
        layer.closeAll();
        table.reload("addonTable");
      }, function (data, res) {
        if (res && res.code === -3) {
          //插件目录发现影响全局的文件
          layer.open({
            content: layui.laytpl($("#conflicttpl").html()).render({list: res.data}),
            shade: 0.8,
            area: area,
            title: '温馨提示',
            btn: ['继续操作', '取消'],
            end: function () {

            },
            yes: function () {
              uninstall(name, true, droptables);
            }
          });
        } else {
          layer.alert(res.msg, {title: '温馨提示', icon: 0});
        }
        return false;
      });
    };

  });
</script>
